/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-06-25
 * Time: 10:31
 */
class Solution17 {
    //标记数组
    boolean[][] visit;
    int m,n;
    char[] word;

    public boolean exist(char[][] board, String word1) {
        word = word1.toCharArray();
        //行数
        m = board.length;
        //列数
        n = board[0].length;
        visit = new boolean[m][n];

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(board[i][j] == word[0]) {
                    visit[i][j] = true;
                    if(dfs(board,i,j,1)) {
                        return true;
                    }
                    //恢复现场
                    visit[i][j] = false;
                }
            }
        }
        return false;
    }
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};

    boolean dfs(char[][] board,int i, int j, int pos) {
        //已经遍历完了 告诉它成了
        if(pos == word.length) {
            return true;
        }

        //上下左右去匹配word[pos]
        //4个dfs
        //利用向量数组，一个for循环解决上下左右四个方向

        for(int k = 0; k < 4; k++) {
            int x = i+dx[k],y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && board[x][y] == word[pos]) {
                visit[x][y] = true;
                if(dfs(board,x,y,pos+1)) {
                    return true;
                }
                visit[x][y] = false;
            }
        }
        return false;
    }
}
